import React, { useEffect, useState } from "react";
import {
  Table,
  Image,
  Switch,
  Space,
  Button,
  Popconfirm,
  Modal,
  Input,
} from "antd";
import sendFetch from "@/fetch";
import { PlusOutlined } from "@ant-design/icons";
import "@/assets/styles/Manager.scss";

const { Column } = Table;

export default function SlideList() {
  interface DataType {
    key: React.Key;
    img: string;
    title: string;
    url: string;
    status: boolean;
    seq: number;
    created_at: string;
  }

  const [data, setData] = useState([]);
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [isNew, setIsNew] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newUrl, setNewUrl] = useState("");
  const [newSeq, setNewSeq] = useState(0);
  const [editId, setEditId] = useState<React.Key>(0);

  const banSlide = (id: number|React.Key, status: boolean) => {
    return () => {
      sendFetch(`/manager/banSlide`, { id: id, status: status }).then(
        (res: any) => {
          getSlideData();
        }
      );
    };
  };

  const getSlideData = () => {
    sendFetch(`/manager/getSlideList`).then((res: any) => {
      setData(res.data);
    });
  };

  const handleOk = () => {
    setConfirmLoading(true);
    sendFetch(isNew ? `/manager/addSlide` : `/manager/editSlide`, {
      id: editId,
      title: newTitle,
      url: newUrl,
      seq: newSeq,
    }).then((res: any) => {
      getSlideData();
      setConfirmLoading(false);
      setNewSeq(0);
      setNewUrl("");
      setNewTitle("");
      setOpen(false);
    });
  };

  const handleCancel = () => {
    setNewSeq(0);
    setNewUrl("");
    setNewTitle("");
    setConfirmLoading(false);
    setOpen(false);
  };

  useEffect(() => {
    getSlideData();
  }, []);

  return (
    <div
      style={{ background: "#fff", padding: "1vh 3vh", borderRadius: "8px" }}
    >
      <Modal
        title="添加用户"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        标题：
        <Input
          type="text"
          id="nt"
          value={newTitle}
          onChange={(e) => {
            setNewTitle(e.target.value);
          }}
        />
        跳转链接：
        <Input
          type="text"
          id="nu"
          value={newUrl}
          onChange={(e) => {
            setNewUrl(e.target.value);
          }}
        />
        排序：
        <Input
          type="number"
          id="np"
          value={newSeq}
          onChange={(e) => {
            setNewSeq(parseInt(e.target.value));
          }}
        />
      </Modal>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          margin: "1vh 0",
        }}
      >
        <p style={{ fontSize: "1.5em" }}>轮播图列表</p>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setIsNew(true);
            setOpen(true);
          }}
        >
          新建
        </Button>
      </div>
      <Table dataSource={data}>
        <Column
          width={100}
          title="图片"
          dataIndex="img"
          key="img"
          render={(_, record: DataType) => (
            <>
              <Image
                style={{
                  height: "5vh",
                  width: "5vh",
                  borderRadius: "50%",
                  overflow: "hidden",
                }}
                src={record.img || "default"}
                fallback=""
              />
            </>
          )}
        />
        <Column title="轮播图名" dataIndex="title" key="title" />
        <Column
          title="跳转链接"
          dataIndex="url"
          key="url"
          render={(_, record: DataType) => {
            return <a href={record.url}>{record.url}</a>;
          }}
        />
        <Column
          title="是否禁用"
          dataIndex="status"
          key="status"
          render={(_, record: DataType) => (
            <>
              <Switch
                checkedChildren="启用"
                unCheckedChildren="禁用"
                checked={record.status}
                onClick={banSlide(record.key, !record.status)}
              />
            </>
          )}
        />
        <Column title="排序" dataIndex="seq" key="seq" />
        <Column title="创建时间" dataIndex="created_at" key="created_at" />
        <Column
          title="操作"
          key="action"
          render={(value, record: DataType) => (
            <Space size="middle">
              <button
                className="hrefButton"
                onClick={() => {
                  setNewTitle(record.title);
                  setNewUrl(record.url);
                  setNewSeq(record.seq);
                  setEditId(record.key);
                  setIsNew(false);
                  setOpen(true);
                }}
              >
                编辑
              </button>
              <Popconfirm
                placement="top"
                title="删除"
                description="您确定要删除吗？"
                onConfirm={() => {
                  sendFetch(
                    `/manager/deleteSlide`,
                    { id: record.key },
                    "GET"
                  ).then(() => {
                    getSlideData();
                  });
                }}
                okText="删除"
                cancelText="取消"
              >
                <button className="hrefButton">删除</button>
              </Popconfirm>
            </Space>
          )}
        />
      </Table>
    </div>
  );
}
